﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Holoville.HOTween;

public partial class BattlefieldFriendScene : Scene
{
	#region - 버튼 이벤트 처리
	public override void BackButton()
	{
		SceneController.LoadLevel("Lobby_4vs4");
	}
	
	public override void ButtonTouch(Collider collider)
	{      
		switch (collider.gameObject.name)
		{
		case "Button - Battle Start":
			OnClick_StartBattle();
			break;
		}
	}

	public void OnClick_StartBattle()
	{
		Debug.Log ("OnClick_StartBattle");

		UserData.Instance.battleFriend = GetSelectedFriend();

		// 전투 친구 없이 진행할 경우
		if (UserData.Instance.battleFriend == null)
		{
			Popup_TwoButton pt = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
			pt.SetPopupWithTitleAndBody(Localization.Get("uiCommonTextwarning"), Localization.Get("uiPopupStandbyCaution1"));
			pt.SetPopupWithYesNoString(Localization.Get("uiCommonTextYes"), Localization.Get("uiCommonTextNo"));
			pt.SetEventOK(this.gameObject, "StartBattleProcess");
		}

		// 전투 친구 데려갈 경우
		else
		{
			UserData.Instance.battleFriendId = UserData.Instance.battleFriend.id;
			UserData.Instance.battleFriendIsMyFriend = GetSelectedFriendIsMyFriend();

			StartBattleProcess();
		}
	}
	#endregion
	
	public void StartBattleProcess()
	{
		// TODO: 왜 있는 것인지 확인 필요
		if (PopupManager.IsPopupExist)
			PopupManager.PopPopup();

		// 1 : 친구 선택하고 진행할 경우
		if (UserData.Instance.battleFriend != null)
		{
			NetworkManager.Instance.C2S_LEGION_FRIEND_GET(UserData.Instance.battleFriendId, (responseData) => {

				if (responseData.ecode != 0)
				{
					PopupUtility.OneButtonErrorPopup(responseData.ecode);
					return;
				}

				// 데려갈 친구 정보 설정
				UserData.Instance.battleFriendUserModel = responseData.data;
				long[] friendInfo = new long[] { UserData.Instance.battleFriendId, (long)UserData.Instance.battleFriendUserModel.choiceMembers[0] };

				// 1 - A : 일일 PVP 일 경우
				if (UserData.Instance.isQuickPVPBattle)
					StartBattleQuickPVP(friendInfo);

				else if (UserData.Instance.counterAttackMsgId > 0)
					StartBattleCounterAttack(friendInfo);


				// 1 - C : 레이드 보스 전투일 경우
				else if (UserData.Instance.raidBossId != 0)
					NetworkManager.Instance.C2S_START_RAIDBOSS_BATTLE(ResponseStartRaidBossBattle, UserData.Instance.battleFriend.id);

				// 1 - D : 그 이외의 전투일 경우
				else
				{
					// 1 - D - (1) : 조사
					if (StandbyScene.startMode == BattleStartMode.Research)
						NetworkManager.Instance.C2S_SEND_TO_RESEARCH(ResponseResearch, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo);

					// 1 - D - (2) : 확장전
					else if( StandbyScene.startMode == BattleStartMode.ExpansionWar )
						NetworkManager.Instance.C2S_SEND_TO_EXPANSION(ResponseExpansion, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.regions.expansionWarStep==0?1:(int)UserData.Instance.userModel.regions.expansionWarStep, UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo);
				}
			});
		}

		// 2 : 친구 없이 진행할 경우
		else
		{
			// 2 - A : 일일 PVP 일 경우
			if (UserData.Instance.isQuickPVPBattle)
				StartBattleQuickPVP();

			else if (UserData.Instance.counterAttackMsgId > 0)
				StartBattleCounterAttack();

			// 2 - C : 레이드 보스 전투일 경우
			else if (UserData.Instance.raidBossId != 0)
				NetworkManager.Instance.C2S_START_RAIDBOSS_BATTLE(ResponseStartRaidBossBattle, 0);

			// 2 - D : 그 이외의 전투일 경우
			else
			{
				// 2 - D - (1) : 조사
				if (StandbyScene.startMode == BattleStartMode.Research)
					NetworkManager.Instance.C2S_SEND_TO_RESEARCH(ResponseResearch, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.choiceMembers.ToArray());

				// 2 - D - (2) : 확장전
				else if( StandbyScene.startMode == BattleStartMode.ExpansionWar )
					NetworkManager.Instance.C2S_SEND_TO_EXPANSION(ResponseExpansion, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.regions.expansionWarStep==0?1:(int)UserData.Instance.userModel.regions.expansionWarStep, UserData.Instance.userModel.choiceMembers.ToArray());
			}
		}
	}

	public void StartBattleQuickPVP(long[] friendInfo = null)
	{
		EPLog.Log ("StartBattleQuickPVP : " + friendInfo);
		NetworkManager.Instance.C2S_QUICK_START(UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo, (responseData) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}
			
			// 빠른 PVP 상대의 UserModel 설정
			UserData.Instance.quickPVPUserModel = responseData.data;
			
			SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01"); // Battle_4vs4_Heights_Verteron_01
		});
	}

	public void StartBattleCounterAttack(long[] friendInfo = null)
	{
		EPLog.Log ("StartBattleCounterAttack : " + friendInfo);
		NetworkManager.Instance.C2S_QUICK_START_IV(UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo, UserData.Instance.counterAttackMsgId, (responseData) => {

			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopup(responseData.ecode);
				return;
			}
			
			// 빠른 PVP 상대의 UserModel 설정
			UserData.Instance.quickPVPUserModel = responseData.data;
			
			SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01"); // Battle_4vs4_Heights_Verteron_01
		});
	}

	#region - 응답 처리
	private void ResponseStartRaidBossBattle(ResponseModel<RaidBossStartModel> result)
	{
		if( result.ecode != 0 )
		{
			Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
			po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
	    	return;
	    }
		StandbyScene.startMode = BattleStartMode.None;
//		if( WorldSceneManager.isSentSearch )
//		{
//			WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
//			WorldSceneManager.sentResearchAreaId = 0;
//			UserData.Instance.researchResultData = null;
//		}
		UserData.Instance.raidBossStartData = result.data;
		UserData.Instance.battleRandomSeed = result.data.seed;

		// 다대다전투 - 레이드 임시로 Battle_Raid_Tiamats_01만 사용.
		SceneController.LoadLevel("Battle_Raid_Tiamats_01");

		//if( result.data.raidBossId == 10001 )
		//	SceneController.LoadLevel("Battle_Boss_Tiamats_01");
		//else
		//	SceneController.LoadLevel("Battle_Boss_Beshmundir_01");
	}

	private void ResponseQuickPvp(ResponseModel<UserModel> result)
	{
		if( result.ecode != 0 )
		{
			Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
			po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
	    }
		StandbyScene.startMode = BattleStartMode.None;
		Debug.Log("ResponseQuickPvp ecode="+result.ecode);
		if (result.ecode != 0)
			return;
		UserData.Instance.battleRandomSeed = Random.Range(1,10000);//임시//
		WorldSceneManager.isSentSearch = false;
		SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01");
	}

	public void ResponseResearch(ResponseModel<ResearchStartModel> result)
	{
		if( result.ecode != 0 )
		{
			Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
			po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
		    return;
	    }
		StandbyScene.startMode = BattleStartMode.None;
		UserData.Instance.battleRandomSeed = result.data.seed;
		WorldSceneManager.isSentSearch = true;
		WorldSceneManager.sentResearchAreaId = WorldSceneManager.GetSelectedAreaId();
		SceneController.LoadLevel(SceneController.GetCurrentBattleSceneName(WorldSceneManager.GetSelectedAreaId()));
	}

	public void ResponseExpansion(ResponseModel<ExpansionWarStartModel> result)
	{
		if( result.ecode != 0 )
		{
			Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
			po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
	    	return;
	    }
		StandbyScene.startMode = BattleStartMode.None;
		UserData.Instance.battleRandomSeed = Random.Range(1,10000);//임시//
		UserData.Instance.extendWarWave1 = result.data.wave1;
		UserData.Instance.extendWarWave2 = result.data.wave2;
		UserData.Instance.extendWarWave3 = result.data.wave3;
		WorldExtensionBattleStageScene.isExpansionWar = true;
		SceneController.LoadLevel(SceneController.GetCurrentBattleSceneName(WorldSceneManager.GetSelectedAreaId()));
	}
	#endregion
}